import { audit, issue, recordByPage, updateBaseInfo, updateOrgBaseInfo } from '@/api/record';
import { DATE_FORMAT } from '@/utils';
import chinaArea from '@/utils/chinaArea';
import {
  applyDataAdapter,
  baseInfoPersonForm,
  baseInfoPersonForm2,
  certiMap,
  certiOptions,
  initDataAdapter,
  statusMap,
  statusOptions,
} from '@/utils/data';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Card,
  Cascader,
  Col,
  DatePicker,
  Descriptions,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Table,
  Upload,
  message,
} from 'antd';
import { DescriptionsProps } from 'antd/lib';
import dayjs from 'dayjs';
import lodash from 'lodash';
import { useEffect, useState } from 'react';

export default () => {
  const [imagePreviewOpen, setimagePreviewOpen] = useState(false);
  const [handleOpen, setHandleOpen] = useState(false);
  const [handleOpen2, setHandleOpen2] = useState(false);
  const [handleOpen3, setHandleOpen3] = useState(false);
  const [data, setData] = useState([]);
  const [editRow, setEditRow] = useState<any>(null);
  const [searchVals, setSearchVals] = useState(null);
  const [editBaseInfo, setEditBaseInfo] = useState(null);
  const [imageData, setImageData] = useState(null);

  const [searchForm] = Form.useForm();
  const [baseInfoForm] = Form.useForm();
  const [qfForm] = Form.useForm();

  const columns = [
    // {
    //   title: '证书编号',
    //   dataIndex: 'certificationId',
    //   key: 'certificationId',
    //   render: (_) => {
    //     return _ || '未知';
    //   },
    // },
    {
      title: '申请时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (_) => {
        return dayjs(_).format(DATE_FORMAT);
      },
    },
    {
      title: '申请类别',
      dataIndex: 'category',
      key: 'category',
      render: (_, record) => {
        if (record.baseInfo.category === 'expiry') return '到期审核';
        return '首次审核';
      },
    },
    {
      title: '办理时长',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (_, record) => {
        if (record.certificationId) return '-';

        return dayjs().diff(dayjs(_), 'day') + '天';
      },
    },
    // {
    //   title: '证书类型',
    //   dataIndex: 'certType',
    //   key: 'certType',
    // },
    {
      title: '申请类型',
      dataIndex: 'certType',
      key: 'certType',
      render: (_) => {
        return certiMap[_] || '未知';
      },
    },
    {
      title: '申请方',
      dataIndex: 'baseInfo',
      key: 'baseInfo',
      render: (_) => {
        return _.name;
      },
    },
    {
      title: '所在地区',
      dataIndex: 'region',
      key: 'region',
      render: (_, record) => {
        return record.baseInfo.region || '暂无';
      },
    },
    {
      title: '证书状态',
      dataIndex: 'status',
      key: 'status',
      render: (_, record) => {
        // if (record.certificationId) return '已办结';
        return (
          <>
            {statusMap[_ || 0] || '未知'}
            {/* <Tag className="mt10" color={record.payStatus != 1 ? 'red' : 'green'}>
              {record.payStatus != 1 ? '未缴费' : '已缴费'}
            </Tag> */}
          </>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 280,
      render: (_, record) => {
        return (
          <div>
            <Button
              size="small"
              type="primary"
              onClick={async () => {
                // const templateResp = await getTemplateDetail({
                //   id: record.templateId,
                // });
                // console.log('😈templateResp', templateResp);
                console.log('😈record.baseInfo.birthDate', record.baseInfo.birthDate);
                console.log('record.baseInfo', record.baseInfo);
                let baseInfoVals = initDataAdapter(record.baseInfo);
                console.log('[baseInfoVals]', baseInfoVals);
                setHandleOpen3(true);
                setEditRow(record);
                setEditBaseInfo(baseInfoVals);
                baseInfoForm.resetFields();
                baseInfoForm.setFieldsValue(baseInfoVals);
              }}
            >
              编辑基础信息
            </Button>
            <Button
              size="small"
              className="ml10"
              type="primary"
              onClick={() => {
                setHandleOpen(true);
                setEditRow(record);
              }}
            >
              处理
            </Button>
            {record.approvedStatus != 2 && (
              <Button
                size="small"
                className="ml10"
                type="primary"
                onClick={() => {
                  setHandleOpen2(true);
                  setEditRow(record);
                  console.log(' record.baseInfo.serialNumber', record.baseInfo.serialNumber);
                  qfForm.resetFields();
                  qfForm.setFieldValue('serialNumber', record.baseInfo.serialNumber);
                }}
              >
                签发
              </Button>
            )}
          </div>
        );
      },
    },
  ];

  const detail = [
    { name: '个人照片', id: 'baseInfo.photoPath' },
    { name: '申请类别', id: 'baseInfo.category' },
    { name: '姓名', id: 'baseInfo.name' },
    { name: '拼音', id: 'baseInfo.pinyin' },
    { name: '性别', id: 'baseInfo.gender' },
    { name: '出生年月', id: 'baseInfo.birthDate' },
    { name: '民族', id: 'baseInfo.nation' },
    { name: '所在地', id: 'baseInfo.address' },
    { name: '籍贯', id: 'baseInfo.nativePlace' },
    { name: '政治面貌', id: 'baseInfo.politicalAffiliation' },
    { name: '联系电话', id: 'baseInfo.mobile' },
    { name: '邮箱', id: 'baseInfo.email' },
    { name: '身份证号码', id: 'baseInfo.cardNo' },
    { name: '邮寄地址', id: 'baseInfo.mailAddress' },
    { name: '教育背景', id: 'baseInfo.eduBg' },
    { name: '工作经历', id: 'baseInfo.workExperience' },
    { name: '所获荣誉', id: 'baseInfo.honors' },
    { name: '推荐机构(推荐人)', id: 'baseInfo.recommend' },
    { name: '所在地区', id: 'baseInfo.region' },
    // { name: '个人照片', id: 'baseInfo.picFile' },
  ];

  const detail2 = [
    { name: '申请类别', id: 'baseInfo.category' },
    { name: '单位名称', id: 'baseInfo.name' },
    { name: '单位地址', id: 'baseInfo.address' },
    { name: '隶属管辖', id: 'baseInfo.subjection' },
    { name: '机构成立时间', id: 'baseInfo.establishmentDate' },
    { name: '单位负责人', id: 'baseInfo.contactUser' },
    { name: '联系电话', id: 'baseInfo.contactPhone' },
    { name: '担任职务', id: 'baseInfo.contactPosition' },
    { name: '校区数量', id: 'baseInfo.campusCount' },
    { name: '校区总面积(平方米)', id: 'baseInfo.totalCampusArea' },
    { name: '学员年龄区间', id: 'baseInfo.studentAgeRange' },
    { name: '舞蹈生在籍人数', id: 'baseInfo.studentsCount' },
    { name: '全职教师人数', id: 'baseInfo.ftTeachersCount' },
    { name: '考级体系', id: 'baseInfo.gradingSystem' },
    { name: '推荐单位(推荐人)', id: 'baseInfo.recommend' },
    { name: '所在地区', id: 'baseInfo.region' },
    { name: '主营课程', id: 'baseInfo.mainCourses' },
    { name: '单位介绍', id: 'baseInfo.description' },
  ];

  const items: DescriptionsProps['items'] = detail
    // .filter((item) => lodash.get(editRow, item.id))
    .map((item, index) => {
      console.log('😈item.id', item.id);
      if (item.id === 'baseInfo.photoPath') {
        return {
          key: index + 1,
          label: item.name,
          span: 2,
          contentStyle: {
            maxWidth: '300px',
          },
          children: (
            <p>
              {lodash.get(editRow, item.id) && (
                <img
                  src={`https://zs.dance2020.cc:16063${lodash.get(editRow, item.id)}`}
                  style={{ height: '200px', width: 'auto' }}
                ></img>
              )}
              {!lodash.get(editRow, item.id) && '暂无'}
            </p>
          ),
        };
      }
      return {
        key: index + 1,
        label: item.name,
        span: 1,
        contentStyle: {
          maxWidth: '300px',
        },
        children: <p>{lodash.get(editRow, item.id) || '暂无'}</p>,
      };
    });

  const items2: DescriptionsProps['items'] = detail2
    .filter((item) => lodash.get(editRow, item.id))
    .map((item, index) => {
      return {
        key: index + 1,
        span: 1,
        label: item.name,
        contentStyle: {
          maxWidth: '300px',
        },
        children: <p>{lodash.get(editRow, item.id) || '暂无'}</p>,
      };
    });

  const init = async () => {
    const resp = await recordByPage({
      pageNo: 1,
      pageSize: 100,
    });
    console.log('😈resps', resp);
    setData(resp?.data?.list || []);
  };

  const search = async () => {
    console.log('😈searchVals', searchVals);
    const resp = await recordByPage({
      pageNo: 1,
      pageSize: 100,
      ...(searchVals || {}),
    });
    console.log('😈resps', resp);
    setData(resp?.data?.list || []);
  };

  const approve = async (approvedStatus) => {
    const resp = await audit({
      id: editRow.id,
      auditResult: approvedStatus,
      autoIssue: true,
    });
    console.log('😈resp', resp);
    if (resp.code === 0) {
      message.success('审核成功');
      search();
      setHandleOpen(false);
    } else {
      message.error(resp.msg);
    }
  };

  const handleIssue = async () => {
    qfForm
      .validateFields({})
      .then(async () => {
        const values = qfForm.getFieldsValue();
        const resp = await issue({
          id: editRow.id,
          ...values,
          availDate: dayjs(values.availDate).format('YYYY-MM-DD'),
        });
        console.log('😈resp', resp);
        if (resp.code === 0) {
          message.success('签发成功');
          search();
          setHandleOpen2(false);
        } else {
          message.error(resp.msg);
        }
      })
      .catch(() => {});
  };

  const handleUpdateBaseInfo = async () => {
    console.log('😈editRow', editRow);
    baseInfoForm.validateFields({}).then(async () => {
      const formValues = baseInfoForm.getFieldsValue();
      console.log('😈formValues', formValues);
      let params = {
        ...editBaseInfo,
        ...formValues,
      };

      if (imageData) {
        params = {
          ...params,
          ...imageData,
        };
      }

      if (!params.pusho) params = applyDataAdapter(params);
      if (editRow?.refObjectType === 'applicant_person') {
        // delete params.id;
        // delete params.certificationId;
        // const resp = await createBaseInfo(params);
        const resp = await updateBaseInfo(params);
        if (resp.code === 0) {
          message.success('更新成功');
          setImageData(null);
          search();
          setHandleOpen3(false);
        } else {
          message.error(resp.msg);
        }
      } else {
        const resp = await updateOrgBaseInfo(params);
        if (resp.code === 0) {
          message.success('更新成功');
          search();
          setHandleOpen3(false);
        } else {
          message.error(resp.msg);
        }
      }
    });
  };

  const RangeNumber = ({ onChange, value }) => {
    const defaultVals = value?.split('-');
    console.log('[defaultVals]', defaultVals);
    const [before, setBefore] = useState(defaultVals?.[0] || 1);
    const [after, setAfter] = useState(defaultVals?.[1] || 100);

    const changeBefore = (val) => {
      onChange(`${val}-${after}`);
      setBefore(val);
    };

    const changeAfter = (val) => {
      onChange(`${before}-${val}`);
      setAfter(val);
    };

    return (
      <div className="flex w100" style={{ alignItems: 'center', gap: '5px' }}>
        <InputNumber
          className="flex-1"
          min={1}
          max={100}
          value={before}
          onChange={changeBefore}
        ></InputNumber>
        <div className=""> - </div>
        <InputNumber
          className="flex-1"
          min={1}
          max={100}
          value={after}
          onChange={changeAfter}
        ></InputNumber>
      </div>
    );
  };

  const renderFormItem = (item) => {
    switch (item.type) {
      case 'select':
        return (
          <Form.Item rules={[{ required: true }]} name={item.key} label={item.label} key={item.key}>
            <Select className="w100" options={item.options}></Select>
          </Form.Item>
        );

      case 'textarea':
        return (
          <Form.Item rules={[{ required: true }]} name={item.key} label={item.label} key={item.key}>
            <Input.TextArea className="w100" rows={5}></Input.TextArea>
          </Form.Item>
        );

      case 'number':
        return (
          <Form.Item rules={[{ required: true }]} name={item.key} label={item.label} key={item.key}>
            <InputNumber className="w100"></InputNumber>
          </Form.Item>
        );

      case 'rangenumber':
        return (
          <Form.Item rules={[{ required: true }]} name={item.key} label={item.label} key={item.key}>
            <RangeNumber></RangeNumber>
          </Form.Item>
        );

      case 'area':
        return (
          <Form.Item rules={[{ required: true }]} name={item.key} label={item.label} key={item.key}>
            <Cascader className="w100" options={chinaArea} placeholder="选择地区" changeOnSelect />
          </Form.Item>
        );

      case 'date':
        return (
          <Form.Item
            rules={[{ required: true, message: '请选择日期!' }]}
            required
            label={item.label}
            key={item.key}
            name={item.key}
          >
            <DatePicker className="w100" format={'YYYY-MM-DD'}></DatePicker>
          </Form.Item>
        );
    }

    return (
      <Form.Item rules={[{ required: true }]} name={item.key} label={item.label} key={item.key}>
        <Input></Input>
      </Form.Item>
    );
  };

  useEffect(() => {
    init();
  }, []);

  return (
    <PageContainer>
      <Modal
        footer={null}
        open={imagePreviewOpen}
        width={600}
        onCancel={() => setimagePreviewOpen(false)}
      >
        <div>
          {imageData?.base64String && (
            <div className="flex flex-col">
              <img
                src={imageData?.base64String}
                style={{ height: 'auto', width: '100%', cursor: 'pointer' }}
                alt=""
              />
            </div>
          )}

          {!imageData?.base64String && editBaseInfo?.photoPath && (
            <div className="flex flex-col">
              <img
                src={`https://zs.dance2020.cc:16063${editBaseInfo?.photoPath}`}
                style={{ height: 'auto', width: '100%', cursor: 'pointer' }}
              ></img>
            </div>
          )}
        </div>
      </Modal>

      <Modal
        title="编辑基础信息"
        open={handleOpen3}
        onCancel={() => {
          setHandleOpen3(false);
          setEditBaseInfo(null);
          setImageData(null);
        }}
        width={900}
        okText={'确认'}
        onOk={handleUpdateBaseInfo}
      >
        <Card title="基础信息">
          {editRow?.refObjectType === 'applicant_person' && (
            <Form labelCol={{ span: 8 }} form={baseInfoForm} initialValues={editBaseInfo}>
              <Row>
                {baseInfoPersonForm.map((item) => {
                  if (item.type === 'image') {
                    return (
                      <Col span={24} key={item.key}>
                        <Form.Item
                          labelCol={{ span: 4 }}
                          rules={[{ required: true }]}
                          name={item.key}
                          label={item.label}
                          key={item.key}
                        >
                          <Upload
                            multiple={false}
                            // beforeUpload={(file) => {
                            //   // 可以在这里添加文件类型或大小的限制逻辑
                            //   // 例如：只允许图片文件上传
                            //   if (!file.type.match('image.*')) {
                            //     message.error('只能上传图片文件！');
                            //     return false;
                            //   }
                            //   // 限制文件大小，例如不超过 2MB
                            //   const isLt2M = file.size / 1024 / 1024 < 5;
                            //   if (!isLt2M) {
                            //     message.error('图片不能超过 5MB!');
                            //     return false;
                            //   }
                            //   return true;
                            // }}
                            customRequest={(info) => {
                              console.log('info', info);
                              if (info.file) {
                                // 获取文件列表中的第一个文件
                                console.log('info', info);
                                const originFileObj = info.file;
                                if (originFileObj) {
                                  // 使用 FileReader 读取文件
                                  const reader = new FileReader();
                                  reader.onload = (e) => {
                                    // 确保读取成功
                                    if (e.target.result) {
                                      // 转换为 base64 编码
                                      const fileBase64 = e.target.result;
                                      console.log('图片 base64 编码:', fileBase64);
                                      const fileName = originFileObj.name;
                                      console.log('文件名称:', fileName);
                                      const pathList = fileBase64.split(',');
                                      console.log(pathList);
                                      const picFile = pathList[pathList?.length - 1];
                                      setImageData({
                                        base64String: fileBase64,
                                        picFile,
                                        picFileName: fileName,
                                      });
                                      // 这里可以设置状态或进行其他操作
                                    }
                                  };
                                  reader.readAsDataURL(originFileObj);
                                }
                              } else if (!info.file) {
                                message.error('图片上传失败');
                              }
                            }}
                            showUploadList={false}
                          >
                            {!editBaseInfo?.photoPath && !imageData?.base64String && (
                              <Button>点击上传</Button>
                            )}

                            {imageData?.base64String && (
                              <div className="flex flex-col">
                                <img
                                  src={imageData?.base64String}
                                  style={{ height: '200px', width: 'auto', cursor: 'pointer' }}
                                  alt=""
                                  onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    setimagePreviewOpen(true);
                                  }}
                                />
                                <Button className="mt10" type="primary">
                                  重新上传
                                </Button>
                              </div>
                            )}

                            {!imageData?.base64String && editBaseInfo?.photoPath && (
                              <div className="flex flex-col">
                                <img
                                  src={`https://zs.dance2020.cc:16063${editBaseInfo?.photoPath}`}
                                  style={{ height: '200px', width: 'auto', cursor: 'pointer' }}
                                  onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    setimagePreviewOpen(true);
                                  }}
                                ></img>
                                <Button className="mt10" type="primary">
                                  重新上传
                                </Button>
                              </div>
                            )}
                          </Upload>
                        </Form.Item>
                      </Col>
                    );
                  }

                  return (
                    <Col span={12} key={item.key}>
                      {renderFormItem(item)}
                    </Col>
                  );
                })}
              </Row>
            </Form>
          )}

          {(editRow?.refObjectType === 'applicant_unit' ||
            editRow?.refObjectType === 'applicant_org') && (
            <Form labelCol={{ span: 10 }} form={baseInfoForm} initialValues={editBaseInfo}>
              <Row>
                {baseInfoPersonForm2.map((item) => {
                  return (
                    <Col span={12} key={item.key}>
                      {renderFormItem(item)}
                    </Col>
                  );
                })}
              </Row>
            </Form>
          )}
        </Card>
      </Modal>

      <Modal
        title="签发"
        open={handleOpen2}
        onCancel={() => setHandleOpen2(false)}
        width={500}
        okText={'签发'}
        onOk={handleIssue}
      >
        <Card>
          <Form labelCol={{ span: 6 }} form={qfForm}>
            <Form.Item name={'availDate'} label="有效期" rules={[{ required: true }]}>
              <DatePicker format={'YYYY-MM-DD'}></DatePicker>
            </Form.Item>
            <Form.Item name={'serialNumber'} label="证书编号">
              <Input disabled={editRow?.baseInfo?.serialNumber}></Input>
            </Form.Item>
          </Form>
        </Card>
      </Modal>

      <Modal
        title="处理"
        open={handleOpen}
        onCancel={() => setHandleOpen(false)}
        footer={null}
        width={900}
      >
        <Card title="申请信息">
          {editRow?.refObjectType === 'applicant_person' && (
            <Descriptions column={2} bordered items={items} />
          )}

          {(editRow?.refObjectType === 'applicant_unit' ||
            editRow?.refObjectType === 'applicant_org') && (
            <Descriptions column={2} bordered items={items2} />
          )}
        </Card>
        <Card title="操作" className="mt10">
          <div className="flex-center">
            <Button
              type="primary"
              onClick={() => {
                approve(3);
              }}
            >
              通过并发送缴费通知
            </Button>
            <Button
              danger
              className="ml10"
              onClick={() => {
                approve(2);
              }}
            >
              不通过
            </Button>
          </div>
        </Card>
      </Modal>
      <Card>
        <Form
          form={searchForm}
          onValuesChange={(_, vals) => {
            const params = { ...vals };
            if (params.applicationTime)
              params.applicationTime = params.applicationTime.map((date) => {
                return dayjs(date).format(DATE_FORMAT);
              });
            console.log('😈params', params);
            setSearchVals(params);
          }}
        >
          <Row gutter={10}>
            <Col span={6}>
              <Form.Item name={'certType'}>
                <Select
                  placeholder="请选择证书类型"
                  className="w100"
                  options={certiOptions}
                  allowClear
                ></Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name={'name'}>
                <Input placeholder="请输入申请方"></Input>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name={'status'}>
                <Select
                  allowClear
                  placeholder="请选择证书状态"
                  className="w100"
                  options={statusOptions}
                ></Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name={'applicationTime'}>
                <DatePicker.RangePicker
                  format={'YYYY-MM-DD'}
                  allowClear
                  placeholder={['申请时间开始', '申请时间结束']}
                  className="w100"
                ></DatePicker.RangePicker>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <div className="flex-bt mt10">
          <div></div>
          <Button type="primary" onClick={search}>
            搜索
          </Button>
        </div>
      </Card>

      <Card className="mt10">
        <Table columns={columns} dataSource={data}></Table>
      </Card>
    </PageContainer>
  );
};
